package com.wjw.java.thread;

/**
 * 线程常用方法1：
 * --------------------------------------------------------------------------------------
 * 1.setName(String name);
 *   给线程设置名称
 * 2.getName();
 *   获取线程名称
 * 3.start();
 *   启动线程,调用Thread类中的start() --> JVM调用native start0()本地方法 -->run()
 * 4.run();
 *   调用线程对象中的run()
 * 5.setPriority();
 *   设置线程的优先级,级别越高,抢到CPU的机会就越大,最小值1,最大值10
 * 6.getPriority();
 *   获取线程的优先级
 * 7.sleep();
 *   线程休眠
 * 8.interrupt();
 *   打断线程,没有真正的结束线程,一般用于打断休眠中的线程(闹钟),会抛出InterruptedException异常
 * --------------------------------------------------------------------------------------
 */
public class ThreadMethod1 {

    public static void main(String[] args) {
        Thread t1 = new Thread(new T2());
        t1.setName("子线程:");
        t1.setPriority(8);
        t1.start();

        //主线程每隔1秒输出1次,当i=0时,主线程打断休眠的子线程t1
        for (int i = 10; i >= 0; i--){
            System.out.println(Thread.currentThread().getName() +":"+i);
            try {
                Thread.sleep(1000);
                if(i == 0){
                    t1.interrupt();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

}
class T2 implements Runnable{
    @Override
    public void run() {
        String name = Thread.currentThread().getName();
        int priority = Thread.currentThread().getPriority();
        System.out.println(name+"的优先级为："+priority);
        for (int i = 0; i < 30; i++) {
            System.out.println(name+"正在吃包子..."+ (i+1));
        }
        System.out.println(name+"吃完了30个包子,开始休眠30秒...");
        try {
            Thread.sleep(30 * 1000);
        } catch (InterruptedException e) {
            //e.printStackTrace();
            //当休眠中的线程执行了interrupt(),会抛出异常InterruptedException
            //此时就会catch到这个异常,可以加入自己的相关业务逻辑
            System.out.println(name+"被interrupt打断了...");
        }
        for (int i = 0; i < 20; i++) {
            System.out.println(name+"继续吃包子..."+ (i+1));
        }
    }
}